﻿using BackendLogic;
using BackendLogic.BaseLogic;
using Ioc.Unity;
using System;
using System.Web.Mvc;

namespace BackstageWeb.App_Start.Helper
{
    /// 用户授权特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class UserAuthorizationAttribute : ActionFilterAttribute
    {
        private int functionType = 1;      //1功能 2页面 
        private bool isValidate = false;   //是否需要验证

        /// <summary>
        /// 验证用户信息
        /// </summary>
        /// <param name="isOrgUser">是否验证</param>
        /// <param name="functionType">操作类型  1功能 2页面</param>
        public UserAuthorizationAttribute(bool isValidate, int functionType)
        {
            this.isValidate = isValidate;
            this.functionType = functionType;
        }

        /// <summary>
        ///  验证用户信息
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            var userInfo = UserSession.GetLoginUser();
            #region 权限验证
            if (isValidate)
            {
                //验证登陆
                if (userInfo != null && userInfo.Code != null)
                {
                    ISysUserService userService = UnityCIContainer.Instance.GetService<ISysUserService>();
                    var result = userService.LoadUserByCode(userInfo.Code);
                    //请求跳转到登录页面
                    if (Convert.ToBoolean(result.Data.IsDeleted) || result.Data.State == 1)
                    {
                        ActionException(filterContext, 600, "登录用户不存在或被停用，请重新登录！", "0");
                    }
                }
                else
                {
                    ActionException(filterContext, 500, "无用户信息，请重新登录！", "0");
                }
            }
            //验证权限(这里验证 大的功能权限)
            string sPath = filterContext.RequestContext.HttpContext.Request.Path.Replace("INDEX", "").TrimEnd('/');
            switch (functionType) //1功能 2页面
            {
                case 1:
                    if (!string.IsNullOrWhiteSpace(sPath) && userInfo != null)
                    {
                        //IFunction function = UnityDIContainer.DIContainer.GetInjectionInstance<IFunction>();
                        //bool result = function.ValidateAuthority(userInfo.RoleCodes, sPath.ToLower());
                        //if (!result)
                        //{
                        //    ActionException(filterContext, 600, "无操作权限！", "1");
                        //}
                    }
                    else
                    {
                        ActionException(filterContext, 600, "无操作权限！", "1");
                    }
                    break;
                case 2:
                    if (!string.IsNullOrWhiteSpace(sPath) && userInfo != null)
                    {
                        //IRole role = UnityDIContainer.DIContainer.GetInjectionInstance<IRole>();
                        //var resulInfo = role.JudgeAuthority(userInfo.RoleCodes, sPath);
                        //if (!resulInfo.Success)
                        //{
                        //    ActionException(filterContext, 600, "无操作权限！", "1");
                        //}
                    }
                    else
                    {
                        ActionException(filterContext, 600, "无操作权限！", "1");
                    }
                    break;
                default:
                    break;
            }
            #endregion
        }

        /// <summary>
        /// 失败返回处理
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="statusCode">
        /// 失败编码
        /// 500 无用户信息，请重新登录！
        /// 600 登录用户不存在或被停用，请重新登录！ </param>
        /// <param name="message">失败信息</param>
        /// <param name="data">返回数据</param>
        public void ActionException(ActionExecutingContext filterContext, int statusCode, string message, string data)
        {
            string url = new UrlHelper(filterContext.RequestContext).Action("Index", "Login");
            //防止ajax调用分部视图出现登陆超时，在局部跳转URL的问题   
            filterContext.HttpContext.Response.ContentType = "text/html";
            //$.messager.alert('登录超时','抱歉，您已登录超时，系统将于3秒后返回登录页重新登录','info')
            filterContext.HttpContext.Response.Write("<script> alert('"+ message + "');setTimeout(function(){ window.location.href='" + url + "';},3000); </script>");
            filterContext.HttpContext.Response.End();
        }
    }
}